import {
  Component,
  EventEmitter,
  Input,
  OnDestroy,
  OnInit,
  Output,
} from '@angular/core';
import { NzSelectModeType } from 'ng-zorro-antd/select';
import { BehaviorSubject, Subject } from 'rxjs';
import { debounceTime, map, switchMap } from 'rxjs/operators';
import { MockService } from 'src/app/services/mock.service';

export interface Options {
  id: string;
  name: string;
}

@Component({
  selector: 'app-fuzzy-search',
  templateUrl: './fuzzy-search.component.html',
  styleUrls: ['./fuzzy-search.component.scss'],
})
export class FuzzySearchComponent implements OnInit, OnDestroy {
  @Input() multiple: NzSelectModeType = 'default';
  @Output() valueChange = new EventEmitter();
  searchValue$ = new Subject<string>();
  destory$ = new Subject();
  selectOptions: Options[] = [];
  isLoading: boolean = false;
  constructor(private mock: MockService) {}

  ngOnInit() {
    this.initSearch();
  }

  ngOnDestroy(): void {
    this.destory$.next();
    this.destory$.complete();
  }

  initSearch() {
    this.searchValue$
      .pipe(
        debounceTime(500),
        switchMap((value) => this.request(value))
      )
      .subscribe((res) => {
        this.isLoading = false;
        console.log('res', res);
        this.selectOptions = res;
      });
  }

  request(type: string) {
    const params = {
      code: 'code111',
      name: `query${type + 1}`,
      id: `query${type + 1}`,
    };
    this.isLoading = true;
    return this.mock.queryData1(params).pipe(map((res) => res.value || []));
  }

  onSearch(value: string) {
    console.log('value', value);
    if (!value) return;
    this.searchValue$.next(value);
  }

  onSelectChange(select: string) {
    console.log('selectChange', select);
    this.valueChange.emit(select);
  }
}
